//
//  XLV2LoginViewController.m
//  XiangLove
//
//  Created by 李传坤 on 2018/6/1.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLV2LoginViewController.h"
#import "XLLLoginView.h"
#import "XLLLoginViewModel.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <UtilsMacro.h>
#import <MBProgressHUD+BMH.h>
#import <WechatOpenSDK/WXApi.h>
#import <WechatOpenSDK/WXApiObject.h>
#import <WechatOpenSDK/WechatAuthSDK.h>
#import "WXApiManager.h"
#import "UIImage+GIF.h"
#import "XLHTTPSessionManager+Login.h"
#import "XLNewMainViewController.h"

#import "XLNavgationViewController.h"
#import "XLOldMainTapViewController.h"
#import <NSString+DeviceId.h>
#import "XLTabBarController.h"
#import "XLWebViewController.h"
#import "CallIncomingListenner.h"
#import "XLDownloadImageTool.h"

NSString *const XLLLoginSuccessNotification = @"XLLLoginSuccessNotification";

@interface XLV2LoginViewController ()<WXApiManagerDelegate>
@property (nonatomic, strong) XLLLoginView *loginView;
@property (nonatomic, strong) XLUserInfoModel *userInfoModel;
@property (nonatomic, strong) UIButton *firstWXLogin;
@property (nonatomic, strong) UIButton *mobileLogin;
@property (nonatomic, strong) UIButton *YKLogin;
@property (nonatomic, strong) UIButton *protocolButton;
@property (nonatomic, strong) UIView *animalViewLeft;
@end

@implementation XLV2LoginViewController

- (void)dealloc
{
    NSLog(@"%s",__func__);
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        if ([XLAccountManager shareInstance].loginViewModel) {
            self.viewModel = [XLAccountManager shareInstance].loginViewModel;
        } else {
            self.viewModel = [[XLLLoginViewModel alloc] init];
            [XLAccountManager shareInstance].loginViewModel = self.viewModel;
        }
    }
    return self;
}

//- (void)loadView {
//    self.loginView = [[XLLLoginView alloc] init];
//    self.view = self.loginView;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showBackButton:NULL];
    if (self.navigationController.viewControllers.count > 1) {
        [self showBackButton:NULL];
    }
    self.fd_prefersNavigationBarHidden = YES;
    
    [WXApiManager sharedManager].delegate = self;
    NSArray *array1 = @[[UIImage imageNamed:@"1.png"],
                        [UIImage imageNamed:@"2.png"],
                        [UIImage imageNamed:@"3.png"],
                        [UIImage imageNamed:@"4.png"],
                        [UIImage imageNamed:@"5.png"],
                        [UIImage imageNamed:@"6.png"],[UIImage imageNamed:@"7.png"],[UIImage imageNamed:@"8.png"],[UIImage imageNamed:@"9.png"],[UIImage imageNamed:@"10.png"],[UIImage imageNamed:@"11.png"],[UIImage imageNamed:@"12.png"],[UIImage imageNamed:@"13.png"],[UIImage imageNamed:@"14.png"],[UIImage imageNamed:@"15.png"],[UIImage imageNamed:@"16.png"],[UIImage imageNamed:@"17.png"],[UIImage imageNamed:@"18.png"]];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    imageView.animationImages = array1;
    imageView.animationDuration = 2;
    imageView.animationRepeatCount = 0;
    [imageView startAnimating];
    [self.view addSubview:imageView];
    self.animalViewLeft = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _animalViewLeft.backgroundColor = RGBA_HEX(0x000000, 0.6);
    [self.view addSubview:_animalViewLeft];
    
 

    
    //游客登录
    self.YKLogin = [UIButton buttonWithType:UIButtonTypeCustom];
    self.YKLogin.frame = CGRectMake(ScreenWidth/2+10, SCREEN_HEIGHT - 80, SCREEN_WIDTH/2 - 30, 40);
    [self.YKLogin setImage:[UIImage imageNamed:@"login_icon_youke_n"] forState:UIControlStateNormal];
    [self.YKLogin setTitle:@" 游客" forState:UIControlStateNormal];
    self.YKLogin.layer.cornerRadius = 5;self.YKLogin.titleLabel.font = kSetFont(15);
    self.YKLogin.layer.borderWidth = 0.5;
    [self.YKLogin addTarget:self action:@selector(YKLogin2) forControlEvents:UIControlEventTouchUpInside];
    self.YKLogin.layer.borderColor = RGBA_HEX(0xffffff, 0.5).CGColor;
    [self.view addSubview:_YKLogin];
    
    //微信登录
    self.firstWXLogin = [UIButton buttonWithType:UIButtonTypeCustom];
    self.firstWXLogin.frame = CGRectMake(25, SCREEN_HEIGHT - 80, SCREEN_WIDTH/2 - 30, 40);
    if ([QudaoName isEqualToString:@"xinliao_openinstall_ios"]) {
        self.firstWXLogin.frame = CGRectMake(25, SCREEN_HEIGHT - 80, SCREEN_WIDTH - 50, 40);
        self.YKLogin.hidden = YES;
    }
    
    [self.firstWXLogin setTitle:@" 微信" forState:UIControlStateNormal];
    [self.firstWXLogin setImage:[UIImage imageNamed:@"login_icon_weixin_n"] forState:UIControlStateNormal];self.firstWXLogin.titleLabel.font = kSetFont(15);
    self.firstWXLogin.layer.cornerRadius = 5;
    self.firstWXLogin.layer.borderWidth = 0.5;
    self.firstWXLogin.layer.borderColor = RGBA_HEX(0xffffff, 0.5).CGColor;
    [[self.firstWXLogin rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        SendAuthReq* req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo" ;
        req.state = @"123" ;
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:req];
    }];
    [self.view addSubview:_firstWXLogin];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        self.YKLogin.frame = CGRectMake(25, SCREEN_HEIGHT - 80, SCREEN_WIDTH - 50, 40);
        self.firstWXLogin.hidden = YES;
    }
    
    //手机登录
//    self.mobileLogin = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.mobileLogin.frame = CGRectMake(40, SCREEN_HEIGHT - 180, SCREEN_WIDTH - 80, 50);
//    [self.mobileLogin setImage:[UIImage imageNamed:@"login_icon_ shouji_n"] forState:UIControlStateNormal];
//    [self.mobileLogin setTitle:@"手机登录" forState:UIControlStateNormal];
//    self.mobileLogin.layer.cornerRadius = 5;
//    self.mobileLogin.layer.borderWidth = 1;
//    [self.mobileLogin addTarget:self action:@selector(mobileLoginVC) forControlEvents:UIControlEventTouchUpInside];
//    self.mobileLogin.layer.borderColor = [UIColor whiteColor].CGColor;
//    [self.view addSubview:_mobileLogin];
    
    [self mobileLoginVC];
    
    
    self.protocolButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.protocolButton.frame = CGRectMake(25, SCREEN_HEIGHT - 112, SCREEN_WIDTH - 80, 20);
    self.protocolButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.protocolButton setTitle:@"登录代表你已同意《服务与隐私条款》" forState:UIControlStateNormal];
    [self.protocolButton addTarget:self action:@selector(protocolH5VC) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_protocolButton];
    self.view.backgroundColor = kWhiteColor;
    
    if ([_isYouKe isEqualToString:@"yes"]) {//绑定
        self.loginView = [[XLLLoginView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [self.loginView makeBindUI];
        @weakify(self);
        self.loginView.LoginViewBlock = ^{
            @strongify(self);
            [self.loginView removeFromSuperview];
        };
        [self bindingData];
        [self.view addSubview: self.loginView];
    }
}
- (void)mobileLoginVC{
    self.loginView = [[XLLLoginView alloc] initWithFrame:CGRectMake(0, 110, SCREEN_WIDTH, 220)];
    [self bindingData];
    [self.view addSubview: self.loginView];
}
- (void)protocolH5VC{
    XLWebViewController *vc = [[XLWebViewController alloc] init];
    vc.url = @"xiangLoveProxy.htm";
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setupIQKeyBoardEnabled:YES];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self setupIQKeyBoardEnabled:NO];
}

- (void)bindingData {
    self.loginView.codeBtn.rac_command = self.viewModel.queryCodeCommand;
    self.loginView.loginButton.rac_command = self.viewModel.loginCommand;
    self.loginView.bindButton.rac_command = self.viewModel.bindCommand;
    
    [self.loginView.codeBtn.rac_command.enabled subscribeNext:^(id x) {
        NSLog(@"codeBtn.enabled = %@", x);
    }];
    
    @weakify(self);
    [self.loginView.phoneField.rac_textSignal subscribeNext:^(NSString *text) {
        @strongify(self);
        if (text.length >= 11) {
            self.loginView.phoneField.text = [text substringWithRange:NSMakeRange(0, 11)];
            if ([[IQKeyboardManager sharedManager] canGoNext]) {
                [[IQKeyboardManager sharedManager] goNext];
            }
        }
        self.viewModel.phone = self.loginView.phoneField.text;
    }];
    
    [self.loginView.codeField.rac_textSignal subscribeNext:^(NSString *text) {
        @strongify(self);
        if (text.length > 6) {
            self.loginView.codeField.text = [text substringWithRange:NSMakeRange(0, 6)];
        }
        self.viewModel.code = self.loginView.codeField.text;
    }];
    
    [self.viewModel.intervalTimeSignal subscribeNext:^(id x) {
        @strongify(self);
        NSInteger intervalTime = [x integerValue];
        if (intervalTime > 0) {
            [self.loginView.codeBtn setTitle:F(@"%zds后重发", intervalTime) forState:UIControlStateNormal];
        }else{
            [self.loginView.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        }
    }];
    
    //监听登录结果
    [[RACObserve(self.viewModel, loginStatus) skip:1]  subscribeNext:^(id x) {
        @strongify(self);
        XLLLoginViewModelStatus status = [x integerValue];
        switch (status) {
            case XLLLoginViewModelStatus_Doing:
                [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                [[IQKeyboardManager sharedManager] resignFirstResponder];
                break;
            case XLLLoginViewModelStatus_Success:{
                [self loginSuccess];
            }
                break;
            case XLLLoginViewModelStatus_Fail:{ //校验失败
                [MBProgressHUD hideHUD];
                [MBProgressHUD hideAllHUDsForView:self.view  animated:YES];
                NSString *errorText = self.viewModel.loginError.userInfo[NSLocalizedDescriptionKey];
                errorText = errorText.length > 0 ? errorText : @"登录失败";
                [MBProgressHUD showContent:errorText toView:self.view];
            }
                break;
            default:
                break;
        }
    }];
    //绑定结果
    [[RACObserve(self.viewModel, BindStatus) skip:1]  subscribeNext:^(id x) {
        @strongify(self);
        XLLLoginViewModelStatus status = [x integerValue];
        switch (status) {
            case XLLLoginViewModelStatus_Success:{
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [MBProgressHUD showContent:@"绑定成功" toView:self.view];
//                [UserDefaults setObject:@"no" forKey:@"isYoukeInfor"];
                XLTabBarController *mainVC = [[XLTabBarController alloc] init];
                [UIApplication sharedApplication].keyWindow.rootViewController = mainVC;
            }
                break;
            case XLLLoginViewModelStatus_Fail:{ //校验失败
                [MBProgressHUD hideHUD];
                NSString *errorText = self.viewModel.BindError.userInfo[NSLocalizedDescriptionKey];
                errorText = errorText.length > 0 ? errorText : @"绑定失败";
                [MBProgressHUD showContent:errorText toView:self.view];
            }
                break;
            default:
                break;
        }
    }];
    //监听获取验证码逻辑结果
    [[RACObserve(self.viewModel, queryCodeStatus) skip:1] subscribeNext:^(id x) {
        @strongify(self);
        NSInteger statueValue = [x integerValue];
        switch (statueValue) {
            case XLLLoginViewModelStatus_Doing:{
                //                [MBProgressHUD showMessage:@"正在获取验证码..." toView:self.view];
            }
                break;
            case XLLLoginViewModelStatus_Success:{
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [MBProgressHUD showContent:@"验证码已发送到您的手机" toView:self.view];
            }
                break;
            case XLLLoginViewModelStatus_Fail:{
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                NSString *errorText = self.viewModel.queryCodeError.userInfo[NSLocalizedDescriptionKey];
                errorText = errorText.length > 0 ? errorText : @"获取验证码失败";
                [MBProgressHUD showContent:errorText toView:self.view];
            }
                break;
            default:
                break;
        }
    }];
    
    //微信登录
    [[self.loginView.WXLoginButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        SendAuthReq* req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo" ;
        req.state = @"123" ;
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:req];
    }];
    [[self.loginView.protocolButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self protocolH5VC];
    }];
    [[self.loginView.bindButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        //        [self protocolH5VC];
    }];
    
}

- (void)setupIQKeyBoardEnabled:(BOOL)enabled {
    [[IQKeyboardManager sharedManager] setEnable:enabled];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:enabled];
}

- (void)loginSuccess {
    [self logOutByb];
    self.userInfoModel = self.viewModel.data;
    [UserDefaults setObject:self.userInfoModel.Id forKey:UserID];
    [UserDefaults setObject:self.userInfoModel.HeadImg forKey:UserHead];
    [UserDefaults setObject:self.userInfoModel.NickName forKey:UserNick];
    [UserDefaults setObject:self.userInfoModel.Token forKey:UserToken];
    [UserDefaults setObject:self.userInfoModel.IsNewUser forKey:NewUser];
    //在登陆账号的时候设置还未请求次数接口
    [UserDefaults setBool:YES forKey:FreeCounts];
    [UserDefaults synchronize];
    [XLHTTPSessionManager attemptDealloc];
    [self loginBoyibo];
}
#pragma mark - 游客登录
- (void)YKLogin2{
    @weakify(self);
    XLHTTPSessionManager *manager = [XLHTTPSessionManager sharedManager];
    manager.cachePloy = XLHTTPCachePloy_Server;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[manager visitorLogin] subscribeNext:^(id x) {
        @strongify(self);
        self.userInfoModel = x;
        [UserDefaults setObject:self.userInfoModel.Token forKey:UserToken];
        [UserDefaults setObject:self.userInfoModel.Id forKey:UserID];
        [UserDefaults setObject:self.userInfoModel.HeadImg forKey:UserHead];
        [UserDefaults setObject:self.userInfoModel.NickName forKey:UserNick];
        [UserDefaults setObject:self.userInfoModel.IsNewUser forKey:NewUser];
        //在登陆账号的时候设置还未请求次数接口
        [UserDefaults setBool:YES forKey:FreeCounts];
        [UserDefaults synchronize];
        [XLHTTPSessionManager attemptDealloc];
        [self loginBoyibo];
    } error:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
        [MBProgressHUD showContent:@"请重试"];
    }];
}
#pragma mark - 微信登录回调
- (void)managerDidRecvAuthResponse:(SendAuthResp *)response {
    int errorCode = response.errCode;
    if (errorCode == 0) {
        [MBProgressHUD showMessage:@""];
        NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", [UserDefaults objectForKey:wxGlobAppID], [UserDefaults objectForKey:wxGlobSECRET], response.code];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSURL *zoneU = [NSURL URLWithString:url];
            NSString *zoneS = [NSString stringWithContentsOfURL:zoneU encoding:NSUTF8StringEncoding error:nil];
            NSData *dat = [zoneS dataUsingEncoding:NSUTF8StringEncoding];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (dat) {
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:dat options:NSJSONReadingMutableContainers error:nil];
                    
                    NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",dic[@"access_token"], dic[@"openid"]];
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        NSURL *zoneU = [NSURL URLWithString:url];
                        NSString *zoneS = [NSString stringWithContentsOfURL:zoneU encoding:NSUTF8StringEncoding error:nil];
                        NSData *dat = [zoneS dataUsingEncoding:NSUTF8StringEncoding];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if (dat) {
                                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:dat options:NSJSONReadingMutableContainers error:nil];
                                XLHTTPSessionManager *manager = [XLHTTPSessionManager sharedManager];
                                manager.cachePloy = XLHTTPCachePloy_Server;
                                [[manager userLoginWithAppUid:dic[@"unionid"]
                                                     wxOpenId:dic[@"openid"]
                                                     userName:dic[@"nickname"]
                                                   headImgUrl:dic[@"headimgurl"]
                                                          sex:[dic[@"sex"] integerValue] == 1 ? UserSex_Male : UserSex_Female
                                                          age:0
                                                  boundSource:BoundSourceType_WX] subscribeNext:^(id x) {
                                    self.userInfoModel = x;
                                    [UserDefaults setObject:self.userInfoModel.Id forKey:UserID];
                                    [UserDefaults setObject:self.userInfoModel.Token forKey:UserToken];
                                    [UserDefaults setObject:self.userInfoModel.HeadImg forKey:UserHead];
                                    [UserDefaults setObject:self.userInfoModel.NickName forKey:UserNick];
                                    [UserDefaults setObject:self.userInfoModel.IsNewUser forKey:NewUser];
                                    //在登陆账号的时候设置还未请求次数接口
                                    [UserDefaults setBool:YES forKey:FreeCounts];
//                                    [UserDefaults setObject:@"no" forKey:@"isYoukeInfor"];
                                    [UserDefaults synchronize];
                                    [XLHTTPSessionManager attemptDealloc];


                                    [self loginBoyibo];
                                } error:^(NSError *error) {
                                    [MBProgressHUD hideHUD];
                                    [MBProgressHUD showContent:@"登录失败"];
                                }];
                            } else {
                                [MBProgressHUD hideHUD];
                                [MBProgressHUD showContent:@"登录失败"];
                            }
                        });
                        
                    });
                } else {
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showContent:@"登录失败"];
                }
            });
        });
    }
}

#pragma mark - 登录腾讯云
- (void)loginBoyibo {
    [self logOutByb];
    
    [[XLAccountManager shareInstance] updateUserInfo:self.userInfoModel];
    
    NSString * useridStr   = self.userInfoModel.Id;
    NSString * boundSource = @"4";
    //时间
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    
    NSString *sTimeUser = [fmt stringFromDate:now];
    NSString *objIDUser = @"0";
    NSString *publicKeyUser = @"BMH2014YDYWB";
    NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@",objIDUser,useridStr, publicKeyUser, sTimeUser];
    natUser = [natUser md5Encrypt];
    
    
    //        if ([JSON[@"result"][@"errcode"] integerValue] != 0) {
    //            [MBProgressHUD hideHUD];
    //            [MBProgressHUD showContent:JSON[@"result"][@"errmsg"]];
    //            return ;
    //        }
    NSString *sign = self.userInfoModel.Sign;
    TIMLoginParam * login_param = [[TIMLoginParam alloc ]init];
    
    // accountType 和 sdkAppId 通讯云管理平台分配
    // identifier为用户名，userSig 为用户登录凭证
    // appidAt3rd 在私有帐号情况下，填写与sdkAppId 一样
    NSString *TXAPPID = TIM_APP_ID_TEST;
    NSString *TXACCOUNTTYPE = TIM_ACCOUNT_TYPE_TEST;
    NSString *xlapi = BaseURL;
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"isTestUrl"]isEqualToString:@"yes"]) {
        xlapi = @"http://test.xinliao.xiuquapp.com";
    }
    if ([xlapi isEqualToString:@"http://xinliao.xiuquapp.com"]) {
        TXAPPID = TIM_APP_ID;   TXACCOUNTTYPE = TIM_ACCOUNT_TYPE;
    }
    login_param.accountType = TXACCOUNTTYPE;
    login_param.identifier = [NSString stringWithFormat:@"%@",self.userInfoModel.Id];
    login_param.userSig = sign;
    login_param.appidAt3rd = TXAPPID;
    login_param.sdkAppId = [TXAPPID intValue];
    
    [[TIMManager sharedInstance] login:login_param succ:^(){
        
        TIMAPNSConfig * apnsConfig = [[TIMAPNSConfig alloc] init];
        apnsConfig.openPush = 1;
        apnsConfig.c2cSound = @"";
        
        [[TIMManager sharedInstance] setAPNS:apnsConfig succ:^() {
            DebugLog(@"nnnnnnnnnnnnnn");
        } fail:^(int code, NSString *err) {
            DebugLog(@"setAPNS fail %d %@",code , err);
        }];
        
        //视频聊天ILiveSDK登录
        [[XLAccountManager shareInstance] updateUserInfo:self.userInfoModel];
        [[ILiveLoginManager getInstance] iLiveLogin:[NSString stringWithFormat:@"%@",self.userInfoModel.Id] sig:sign succ:^{
            [MBProgressHUD hideHUDForView:self.view];

            [MBProgressHUD hideHUD];
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
            [MBProgressHUD showContent:@"登录成功"];
            [[XLAccountManager shareInstance] updateUserInfo:self.userInfoModel];
            if ([self.userInfoModel.IsAnchor isEqualToString:@"1"]) {
                [self joinGroup];
            }
            XLTabBarController *mainVC = [[XLTabBarController alloc] init];
            [UIApplication sharedApplication].keyWindow.rootViewController = mainVC;
            [[[UIApplication sharedApplication] keyWindow] makeKeyAndVisible];
                    [self dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                   
//                }
//            });
        } failed:^(NSString *moudle, int errId, NSString *errMsg) {
            //登录失败
            [MBProgressHUD hideHUD];
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
            [MBProgressHUD showContent:@"登录失败"];
        }];
    } fail:^(int code, NSString * err) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD hideHUDForView:self.view animated:NO];
        [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
        if (code != 6015) {
            [MBProgressHUD showContent:@"登录失败"];
        }
    }];
}

- (void)joinGroup {
    [[TIMGroupManager sharedInstance] JoinGroup:@"10086" msg:@"" succ:^{
        [[TIMGroupManager sharedInstance] ModifyGroupMemberInfoSetNameCard:@"10086" user:[[XLAccountManager shareInstance] model].Id nameCard:@"1" succ:^{
            
        } fail:^(int code, NSString *msg) {
        }];
    } fail:^(int code, NSString *msg) {
        if (code == 10013) {
            [[TIMGroupManager sharedInstance] ModifyGroupMemberInfoSetNameCard:@"10086" user:[[XLAccountManager shareInstance] model].Id nameCard:@"1" succ:^{
            } fail:^(int code, NSString *msg) {
            }];
        } else {
            [MBProgressHUD showContent:@"加群失败" toView:self.view];
        }
    }];
}


- (void)logOutByb {

}

@end
